import random
from datetime import datetime

import uvicorn
from fastapi import FastAPI, Depends, HTTPException
from fastapi.params import Query
from sqlalchemy import or_
from sqlalchemy.orm import Session, defer, joinedload, load_only
from fastapi.middleware.cors import CORSMiddleware

from database import get_db_session
from models import Car, Record

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)


@app.get('/')
def index():
    return {'code': 10000, 'message': 'Hello, FastAPI!'}


@app.get('/api/records')
def search(
        page: int = Query(1, gt=0),
        size: int = Query(5, ge=5, le=50),
        keyword: str = Query(None),
        session: Session = Depends(get_db_session)
):
    query = session.query(Record).filter_by(is_deleted=False)\
        .options(
            defer(Record.is_deleted), defer(Record.deleted_time),
            defer(Record.updated_time), defer(Record.car_id)
        ).options(
            joinedload(Record.car).options(load_only(Car.carno, Car.owner))
        ).order_by(Record.makedate.desc())
    if keyword:
        query = query.join(Car).filter(or_(
            Car.owner.contains(keyword), Car.carno.startswith(keyword)
        ))
    total_page = (query.count() - 1) // size + 1
    records = query.offset((page - 1) * size).limit(size).all()
    return {'code': 10000, 'records': records, 'totalPage': total_page}


@app.put('/api/records/{no}')
def handle_record(no: int, session: Session = Depends(get_db_session)):
    record = session.query(Record)\
        .options(load_only(Record.dealt, Record.updated_time))\
        .get(no)
    if record:
        if not record.dealt:
            record.dealt = True
            record.updated_time = datetime.now()
        return {'code': 10000, 'message': '已受理'}
    raise HTTPException(status_code=404, detail='没有对应的违章记录')


@app.delete('/api/records/{no}')
def delete_record(no: int, session: Session = Depends(get_db_session)):
    record = session.query(Record)\
        .options(load_only(Record.is_deleted, Record.deleted_time))\
        .get(no)
    if record:
        if record.dealt:
            record.is_deleted = True
            record.deleted_time = datetime.now()
            return {'code': 10000, 'message': '已删除'}
        else:
            return {'code': 10001, 'message': '不能删除未受理的违章记录'}
    raise HTTPException(status_code=404, detail='没有对应的违章记录')


@app.get('/api/data')
def get_bar_data(session: Session = Depends(get_db_session)):
    # result = session.execute(
    #     'select year(makedate) as year, count(id) as total '
    #     'from tb_record group by year'
    # )
    # x_data, y1_data = [], []
    # for year, total in result.fetchall():
    #     x_data.append(year)
    #     y1_data.append(total)
    x_data = [2017, 2018, 2019, 2020]
    y1_data = [random.randint(5, 12) for _ in range(4)]
    y2_data = [random.randint(5, 12) for _ in range(4)]
    y3_data = [random.randint(5, 12) for _ in range(4)]
    y4_data = [random.randint(5, 12) for _ in range(4)]
    return {'xData': x_data, 'y1Data': y1_data,
            'y2Data': y2_data, 'y3Data': y3_data, 'y4Data': y4_data}


if __name__ == '__main__':
    print('Welcome to Python')
    uvicorn.run('main:app', reload=True)
